﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;

namespace FishServe.Core
{
    public class InjectChildContainerResolver : IDependencyResolverPolicy
    {
        private readonly string _name;
        private readonly Type _typeToResolve;

        public InjectChildContainerResolver(Type typeToResolve)
            : this(typeToResolve, null)
        {
        }

        public InjectChildContainerResolver(Type typeToResolve, string name)
        {
            _name = name;
            _typeToResolve = typeToResolve;
        }

        public object Resolve(IBuilderContext context)
        {
            return this.CreateChildContainer(context);
        }

        protected virtual IUnityContainer CreateChildContainer(IBuilderContext context)
        {
            IUnityContainer childContainer = null;

            IBuilderContext parentContainerContext = context.CloneForNewBuild(new NamedTypeBuildKey(_typeToResolve, _name), null);
            IUnityContainer parentContainer = parentContainerContext.Strategies.ExecuteBuildUp(parentContainerContext) as IUnityContainer;

            if (parentContainer != null)
            {
                childContainer = parentContainer.CreateChildContainer();
            }

            return childContainer;
        }
    }
}
